/*
 * @version: 1.0
 * @Author: zhl
 * @Date: 2021-09-10 15:53:38
 * @LastEditors: zhl
 * @LastEditTime: 2021-09-30 11:49:21
 * @Description: 文件实现描述
 */
#include "GET-Request.h"
#include "dlt698_global.h"
#include <string.h>
#include "hex.h"

GETRequest GETRequest::c_instance;

GETRequest::GETRequest(/* args */){
    c_piid.fields.sn = 0;
    c_piid.fields.reserve = 0;
    c_piid.fields.priority = 0;
}

GETRequest::~GETRequest(){

}

GETRequest *GETRequest::getInstance(){
    return &c_instance;
}

PIID GETRequest::get_piid(){
    std::lock_guard<std::mutex> lock(c_piid_mutex);
    c_piid.fields.sn= 0;
    if(c_piid.fields.sn > 63){
        c_piid.fields.sn = 0;
    }
    return c_piid;
}

int GETRequest::get_request(std::shared_ptr<CConfigManager> cm, TASK_PARAMS *task_params,  uint8_t *apdu, int len){
    if((NULL == task_params) || (task_params->items.empty()) || (NULL == apdu) || (1 > len)){
        return -1;
    }
    int offset = 0;
    int arr_num = 0;
    int arr_num_offset = offset;

    for(auto it = task_params->items.begin(); it != task_params->items.end(); it++){
        auto task_item = cm->get_item(it->item_id);
        if(nullptr == task_item){
            continue ;
        }
        auto dlt698_request = cm->get_dlt698_request(task_item->task_item_id);
        if(nullptr == dlt698_request){
            continue ;
        }
        arr_num++;
        if(arr_num > 1){
            break;
        }
    }

    if(1 == arr_num){
        *apdu = (uint8_t)GET_REQUEST_NORMAL;
        offset += 1;
        *(apdu+offset) = get_piid().value;
        offset += 1;
    }else if(1 < arr_num){
        *apdu = (uint8_t)GET_REQUEST_NORMAL_LIST;
        offset += 1;
        *(apdu+offset) = get_piid().value;
        offset += 1;
        arr_num_offset = offset;
        *(apdu+offset) = (uint8_t)task_params->items.size();
        offset += 1;
    }else{
        return -1;
    }
    arr_num = 0;
    for(auto it = task_params->items.begin(); it != task_params->items.end(); it++){
        auto task_item = cm->get_item(it->item_id);
        if(nullptr == task_item){
            continue ;
        }

        int oad_len = sizeof(OAD_TYPE);
        unsigned char oad[oad_len] = {0};

        auto dlt698_request = cm->get_dlt698_request(task_item->task_item_id);
        if(nullptr == dlt698_request){
            continue ;
        }
        str_to_hex((const char *)dlt698_request->oad.c_str(), oad, &oad_len);
        memcpy(apdu+offset,oad, oad_len);
        offset += oad_len;
        arr_num++;
    }
    if(1 < arr_num){
        *(apdu+arr_num_offset) = (uint8_t)arr_num;
    }

    return offset;
}

int GETRequest::get_request_next(int request_id, uint8_t *apdu, int len, PIID piid){
    if((NULL == apdu) || (1 > len)){
        return -1;
    }
    int offset = 0;
    *apdu = (uint8_t)GET_REQUEST_NEXT;
    offset += 1;
    *(apdu+sizeof(uint8_t)) = piid.value;
    offset += 1;
    return offset;
}